<?php
/**
 * Created by PhpStorm.
 * User: tiemeng
 * Date: 16/3/22
 * Time: 09:17
 */
class goodsModel{
    private $_db;
    private $_table;
    public function __construct(& $base)
    {
        $this->base = $base;
        $this->base->in_erpDb();
        $this->redis = &$this->base->redis;
        $this->_db = &$this->base->erpDb;
        $this->_table = "r_goods";
    }

    /**
     * 通过id获取商品信息
     * @param $id
     * @return mixed
     */
    public function getGoodsById($id){
        return $this->_db->getRow("select * from {$this->_table} where id = '$id' and is_show=1");
    }

    /**
     * 更新商品数量
     * @param $goods_id
     * @param $num
     * @return mixed
     */
    public function updateNum($goods_id,$num){
        return $this->_db->query("update {$this->_table} set num = num-$num where id = '$goods_id'");
    }
    
    /*
     * 购买商品时更新商品数量
     */
    public function buyGoods($goods_id,$num){
        return $this->_db->query("update {$this->_table} set num = num-{$num} , buy_num = buy_num + {$num} where id={$goods_id}");
    }

    /**
     * 检测商品数量
     * @param $goods_id
     * @param $num
     * @return bool
     */
    public function checkNum($goods_id, $num){
        $goodsInfo = $this->_db->getRow("select num,limit_num from {$this->_table} where id='{$goods_id}'");
        if(($goodsInfo['limit_num'] == -1 && $num > $goodsInfo['num']) || ($goodsInfo['limit_num'] > 0 && $num > $goodsInfo['limit_num'])){
            return false;
        }
        return true;
    }

    /**
     * 获取商品列表
     * @param string $where
     * @param int $offset
     * @param int $limit
     * @return mixed
     */
    public function getGoodsList($where = '1',$offset=0,$limit=0){
        if(empty($limit)){
            $sql = "select * from {$this->_table} where is_show = 1 and $where order by id desc";
            return $this->_db->getAll($sql);
        }
        $sql = "select * from {$this->_table} where is_show = 1  $where order by id desc limit {$offset},{$limit}";
        return $this->_db->getAll($sql);
    }

    /**
     * 获取某一分类的商品
     * @param int $catId
     * @return mixed
     */
    public function getGoodsByCategory($catId = 0){
        if(empty($catId)){
            return $this->getGoodsList();
        }else{
            return $this->_db->getAll("select * from {$this->_table} where is_show = 1 and cid='{$catId}'");
        }
    }

    /**
     * 添加赛事商品
     * @param $object_id  赛事ID
     * @param $product_id  货品ID
     * @param $stand_id   规格商品ID
     * @param $stock_num   库存数量
     * @param $sale_price   售价
     * @return mixed
     */
    public function addRaceGoods($object_id,$product_id,$stand_good_id,$stock_num,$sale_price,$sort=0) {
        if (!is_numeric($object_id) || !$object_id
            || !is_numeric($product_id) || !$product_id
            || !is_numeric($stand_good_id) || !$stand_good_id){
            return false;
        }
        return $this->base->load('adminErp')->addObjectGoods(1,$object_id,$product_id,$stand_good_id,(int)$stock_num,(float)$sale_price,$sort);
    }

    /**
     * 删除赛事商品
     * @param $objectId 赛事ID
     * @param $pid  货品ID
     * @param int $standGoodId  可选 规格商品ID
     * @return mixed
     */
    public function saveRaceStatus($objectId,$pid,$standGoodId=0) {
        return $this->base->load('adminErp')->saveObjectStatus(1,$objectId,$pid,$standGoodId);
    }

    /**
     * 查询赛事商品
     * @param $objectId 赛事ID
     */
    public function getRaceGoodsList($objectId) {
        $result = [];
        $list = $this->base->load('adminErp')->getObjectGoodsList($objectId,1);
        if(!$list) return $result;
        foreach ($list as $key=>$val) {
            if (!array_key_exists($val['product_id'],$result)) {
                $result[$val['product_id']]['id'] = $val['id'];
                $info = $this->base->load('adminErp')->getProductInfo($val['product_id'],'id,title,is_virtual');
                $arrImageList = $this->base->load('adminErp')->getProductImage($val['product_id']);
                $arrOneImage = [];
                if ($arrImageList) {
                    foreach($arrImageList as $k=>$v) {
                        $arrOneImage[] = $v['image_url'];
                    }
                }
                $result[$val['product_id']]['product'] = $info ? $info : [];
                $result[$val['product_id']]['sort'] = $val['sort'];
                $result[$val['product_id']]['imageCnt'] = count($arrOneImage);
                $result[$val['product_id']]['imageList'] = $arrOneImage;
                $result[$val['product_id']]['childGoods'] = [];
            }
            //查询规格商品的属性串
            $arrAttrPath = $this->base->load('adminErp')->getGoodsInfo($val['stand_good_id'],'attr_path');
            $strAttrPathName = '';
            $arrAttrList     = [];
            if ($arrAttrPath) {
                $strAttrPathName = $this->base->load('adminErp')->getAttrPathName($val['product_id'],$arrAttrPath['attr_path']);//查询属性值
                $arrAttrList = $this->base->load('adminErp')->getMergeAttrList($val['product_id'],$arrAttrPath['attr_path']);//查询规格商品 属性组合 {id:$id,name:$name}……
            }
            $raceGoods = [];
            $raceGoods['attrPathName'] = $strAttrPathName;
            $raceGoods['attr'] = $arrAttrList;
            $raceGoods['id'] = $val['id'];
            $raceGoods['stockNum'] = $val['stock_num'];
            $raceGoods['saleNum'] = $val['sale_num'];
            $raceGoods['saleprice'] = $val['sale_price'];
            $result[$val['product_id']]['childGoods'][] = $raceGoods;//查询商品
        }
        sort($result);
        return $result;
    }

    /**
     * 查询某个规格商品的信息
     * @param $id  规格商品ID
     * @return array
     */
    public function getRaceGoodsInfo($id) {
        $result =[];
        $raceGoodsinfo = $this->base->load('adminErp')->getObjectGoodsInfo($id);
        if (!$raceGoodsinfo) return $result;
        $info = $this->base->load('adminErp')->getProductInfo($raceGoodsinfo['product_id'],'id,code,title,is_virtual');
        $result['product'] = $info ? $info : [];
        //查询规格商品的属性串
        $arrAttrPath = $this->base->load('adminErp')->getGoodsInfo($raceGoodsinfo['stand_good_id'],'attr_path,real_stock_num');
        $strAttrPathName = '';
        if ($arrAttrPath) {
            $strAttrPathName = $this->base->load('adminErp')->getAttrPathName($raceGoodsinfo['product_id'],$arrAttrPath['attr_path']);//查询属性值
        }

        $arrImageList = $this->base->load('adminErp')->getProductImage($raceGoodsinfo['product_id']);
        $arrOneImage = [];
        if ($arrImageList) {
            foreach($arrImageList as $k=>$v) {
                $arrOneImage[] = $v['image_url'];
            }
        }
        $result['product']['imageCnt'] = count($arrOneImage);
        $result['product']['imageList'] = $arrOneImage;

        $raceGoods = [];
        $raceGoods['id'] = $raceGoodsinfo['id'];
        $raceGoods['attrPathName'] = $strAttrPathName;
        $raceGoods['stockNum'] = $raceGoodsinfo['stock_num'];
        $raceGoods['saleNum'] = $raceGoodsinfo['sale_num'];
        $raceGoods['saleprice'] = $raceGoodsinfo['sale_price'];
        $raceGoods['erpRealStockNum'] = isset($arrAttrPath['real_stock_num']) ? (int)$arrAttrPath['real_stock_num'] : 0;
        $raceGoods['erpGoodId'] = $raceGoodsinfo['stand_good_id'];
        $result['goodsInfo'] = $raceGoods;
       return $result;
    }

    /**
     * 查询所有属性,通过货品ID
     * @param $pid
     * @return array
     */
    public function getAllAttrByPid($pid) {
        return $this->base->load('adminErp')->getAllAttrByPid($pid);
    }

    /**
     * 赛事商品售出
     * @param $gid 商品ID
     * @param $num
     * @return mixed
     */
    public function saleRaceGoods($gid, $num=1) {
       return  $this->base->load('adminErp')->saleObjectGoods($gid, $num);
    }

    /**
     * 闪购商品售出
     * @param $gid 商品ID
     * @param $num
     * @return mixed
     */
    public function saleFlashGoods($gid, $num=1) {
        return  $this->base->load('adminErp')->saleObjectGoods($gid, $num);
    }

    /**
     * 订单超时未付款等，赛事商品购买数量回滚
     * @param $gid 商品ID
     * @param $num
     * @return mixed
     */
    public function rollbackRaceGoodsSaleNum($gid, $num=1) {
        return  $this->base->load('adminErp')->rollbackObjectGoodsSaleNum($gid, $num);
    }

    /**
     * 订单超时未付款等，闪购商品购买数量回滚
     * @param $gid 商品ID
     * @param $num
     * @return mixed
     */
    public function rollbackFlashGoodsSaleNum($gid, $num=1) {
        return  $this->base->load('adminErp')->rollbackObjectGoodsSaleNum($gid, $num);
    }

    /**
     * 添加闪购商品
     * @param $object_id  闪购ID
     * @param $product_id  货品ID
     * @param $stand_id   规格商品ID
     * @param $stock_num   库存数量
     * @param $sale_price   售价
     * @return mixed
     */
    public function addFlashGoods($object_id,$product_id,$stand_good_id,$stock_num,$sale_price,$sort=0) {
        if (!is_numeric($object_id) || !$object_id
            || !is_numeric($product_id) || !$product_id
            || !is_numeric($stand_good_id) || !$stand_good_id){
            return false;
        }
        return $this->base->load('adminErp')->addObjectGoods(adminErpModel::FLASHSHOP,$object_id,$product_id,$stand_good_id,(int)$stock_num,(float)$sale_price,$sort);
    }

    /**
     * 删除闪购商品
     * @param $objectId 闪购ID
     * @param $pid  货品ID
     * @param int $standGoodId  可选 规格商品ID
     * @return mixed
     */
    public function saveFlashStatus($objectId,$pid = 0,$standGoodId=0) {
        return $this->base->load('adminErp')->saveObjectStatus(adminErpModel::FLASHSHOP,$objectId,$pid,$standGoodId);
    }

    /**
     * 查询闪购商品
     * @param $objectId 闪购ID
     */
    public function getFlashGoodsList($objectId) {
        $result = [];
        $list = $this->base->load('adminErp')->getObjectGoodsList($objectId,adminErpModel::FLASHSHOP);
        if(!$list) return $result;
        foreach ($list as $key=>$val) {
            if (!array_key_exists($val['product_id'],$result)) {
                $result[$val['product_id']]['id'] = $val['id'];
                $info = $this->base->load('adminErp')->getProductInfo($val['product_id'],'id,title,is_virtual,express_fee');
                $arrImageList = $this->base->load('adminErp')->getProductImage($val['product_id']);
                $arrOneImage = [];
                if ($arrImageList) {
                    foreach($arrImageList as $k=>$v) {
                        $arrOneImage[] = $v['image_url'];
                    }
                }
                $result[$val['product_id']]['product'] = $info ? $info : [];
                $result[$val['product_id']]['sort'] = $val['sort'];
                $result[$val['product_id']]['imageCnt'] = count($arrOneImage);
                $result[$val['product_id']]['imageList'] = $arrOneImage;
                $result[$val['product_id']]['childGoods'] = [];
            }
            //查询规格商品的属性串
            $arrAttrPath = $this->base->load('adminErp')->getGoodsInfo($val['stand_good_id'],'attr_path');
            $strAttrPathName = '';
            $strAttrPathId = '';
            $arrAttrList     = [];
            if ($arrAttrPath) {
                $strAttrPathName = $this->base->load('adminErp')->getAttrPathName($val['product_id'],$arrAttrPath['attr_path']);//查询属性值
                $strAttrPathId = $this->base->load('adminErp')->getAttrPathId($val['product_id'],$arrAttrPath['attr_path']);//查询属性值
                $arrAttrList = $this->base->load('adminErp')->getMergeAttrList($val['product_id'],$arrAttrPath['attr_path']);//查询规格商品 属性组合 {id:$id,name:$name}……
            }
            $raceGoods = [];
            $raceGoods['attrPathName'] = $strAttrPathName;
            $raceGoods['attrPathId'] = $strAttrPathId;
            $raceGoods['attr'] = $arrAttrList;
            $raceGoods['id'] = $val['id'];
            $raceGoods['stockNum'] = $val['stock_num'];
            $raceGoods['saleNum'] = $val['sale_num'];
            $raceGoods['saleprice'] = $val['sale_price'];
            $result[$val['product_id']]['childGoods'][] = $raceGoods;//查询商品
        }
        sort($result);
        return $result;
    }

    /**
     * 闪购 查询某个规格商品的信息
     * @param $id  规格商品ID
     * @return array
     */
    public function getFlashGoodsInfo($id) {
        $result =[];
        $flashGoodsinfo = $this->base->load('adminErp')->getObjectGoodsInfo($id);
        if (!$flashGoodsinfo) return $result;
        $info = $this->base->load('adminErp')->getProductInfo($flashGoodsinfo['product_id'],'id,code,title,is_virtual,express_fee');
        $result['product'] = $info ? $info : [];
        //查询规格商品的属性串
        $arrAttrPath = $this->base->load('adminErp')->getGoodsInfo($flashGoodsinfo['stand_good_id'],'attr_path,real_stock_num');
        $strAttrPathName = '';
        if ($arrAttrPath) {
            $strAttrPathName = $this->base->load('adminErp')->getAttrPathName($flashGoodsinfo['product_id'],$arrAttrPath['attr_path']);//查询属性值
        }

        $arrImageList = $this->base->load('adminErp')->getProductImage($flashGoodsinfo['product_id']);
        $arrOneImage = [];
        if ($arrImageList) {
            foreach($arrImageList as $k=>$v) {
                $arrOneImage[] = $v['image_url'];
            }
        }
        $result['product']['imageCnt'] = count($arrOneImage);
        $result['product']['imageList'] = $arrOneImage;

        $flashGoods = [];
        $flashGoods['id'] = $flashGoodsinfo['id'];
        $flashGoods['attrPathName'] = $strAttrPathName;
        $flashGoods['stockNum'] = $flashGoodsinfo['stock_num'];
        $flashGoods['saleNum'] = $flashGoodsinfo['sale_num'];
        $flashGoods['saleprice'] = $flashGoodsinfo['sale_price'];
        $flashGoods['erpRealStockNum'] = isset($arrAttrPath['real_stock_num']) ? (int)$arrAttrPath['real_stock_num'] : 0;
        $flashGoods['erpGoodId'] = $flashGoodsinfo['stand_good_id'];
        $result['goodsInfo'] = $flashGoods;
        return $result;
    }

    /*
     * 获取海淘商品pid gid
     */
    public function  getHaitaoPidGid($id){
        $sql = "select code,price from r_goods where id = (select stand_good_id from  r_object_goods where id=$id)";
        $result = $this->base->in_db('erpManageDb')->getRow($sql);
        $code = $result['code'];
        $price = $result['price'];
        $arr = explode("_",$code);
        return array('goods_id'=>$arr[1],'sku_id'=>$arr[2],'price'=>$price);
    }

    /**
     * 跑步有道入口增加限时闪购商品信息
    */
    public function getHomeFlashInfo() {
        //最新的闪购
        $info =  $this->base->db->getRow("select * from r_flash_sales where type in (1,2) and status in(0,5) and total_num>0 and is_featured=1 order by update_time desc  limit 1");
        $result = [];
        if (!$info) return (object)$result;
        $result['id'] = (int)$info['id'];
        $result['url']= 'http://'.$this->base->config['host'].'/show/flashSales?saleId='.(int)$info['id'];
        $result['imageUrl']= $info['image'];
        $result['cardName'] = '限时闪购';
        $result['title'] = $info['title'];
        $result['warmupTime'] = $info['warmup_time'] ? $info['warmup_time'] : 0;
        $result['startTime'] = $info['start_time'];
        $result['endTime']   = $info['end_time'];
        $result['currentTime'] = time();
        $result['costPrice'] = (float)$info['cost_price'];
        $sql  = "select sale_price from r_object_goods where object_id={$info['id']} and type=5 and status=0 ORDER by sale_price limit 1";
        //$salePrice = $this->base->in_db('erpManageDb')->getOne($sql);
        //$result['goodsPrice'] = $salePrice ? (float)$salePrice : 0;
        $result['goodsPrice'] = $info['low_price'];
        return $result;
    }


    public function getObjectGoodsId($stand_good_id,$flash_id=''){
        $result = array();
        $where = " stand_good_id={$stand_good_id} and type=5 and status=0";
        if(!empty($flash_id)){
            $where = " stand_good_id={$stand_good_id} and type=5 and object_id={$flash_id}";
        }
        $sql  = "select id,object_id,product_id,stock_num,sale_num,sale_price,status from r_object_goods where {$where} order by id desc";
        $row = $this->base->in_db('erpManageDb')->getRow($sql);
        if(!empty($row)) {
            $result['object_goods_id'] = $row['id'];
            $result['flash_id'] = $row['object_id'];
            $result['stock_num'] = $row['stock_num'];
            $result['sale_num'] = $row['sale_num'];
            $result['sale_price'] = $row['sale_price'];
            $result['status'] = $row['status'];
            $result['express_fee'] = $this->base->in_db('erpManageDb')->getOne("select express_fee from r_product where id={$row['product_id']}");
        }
        $attrPath = $this->base->in_db('erpManageDb')->getOne("select attr_path from r_goods where id={$stand_good_id}");
        $arr = explode(',',$attrPath);
        $result['atrr'] = array();
        foreach($arr as $v){
            $sql = "select (select title from r_goodattr_head where id=head_id) as head,title as value,img_source from r_goodattr_value where id=$v";
            $row = $this->base->in_db('erpManageDb')->getRow($sql);
            $result['atrr'][] = $row;
        }

        return $result;
    }

    public function getObjectStandGoodsById($ogid){
        return $this->base->in_db('erpManageDb')->getRow("select stand_good_id,object_id from r_object_goods where id=$ogid ");
    }

    public function checkStock($aids,$nums){
        $arrIds = explode(",",$aids);
        $arrNums = explode(",",$nums);
        foreach ($arrIds as $k=>$v){
            $sql = "select sum(stock_num)-sum(sale_num) r_object_goods from r_object_goods where id = $v";
            $stock = $this->base->in_db('erpManageDb')->getOne($sql);
            if($stock-$arrNums[$k]<0){
                return false;
            }
        }
        return true;
    }

    public function getDescartes() {
        $t = func_get_args();
        if(func_num_args() == 1) return call_user_func_array( [$this,__FUNCTION__], $t[0] );
        $a = array_shift($t);
        if(! is_array($a))
            $a = array($a);
        $a = array_chunk($a, 1);

        do {
            $r = array();
            $b = array_shift($t);
            if(! is_array($b)) $b = array($b);

            foreach($a as $p)
                foreach(array_chunk($b, 1) as $q)
                    $r[] = array_merge($p, $q);
            $a = $r;
        }while($t);

        return $r;
    }

}